import logging
import os

from flask import Blueprint, request
from flask import jsonify
from sqlalchemy.orm import Session

from airflow.models.idata_project import Project
from airflow.patsnap.store.resource_sync import S3Resource
from airflow.utils.session import provide_session
from airflow.www.api import exception_handle, provide_user

log = logging.getLogger(__name__)

api_speech_file = Blueprint('api_speech_file', __name__)


# user route
@api_speech_file.route('/files', methods=['GET'])
@exception_handle
def get_files():
    path = request.args.get('path', "", type=str)
    result = S3Resource.list_file(S3Resource(), path)
    return jsonify(code=0, message='ok', data=result)


# user route
@api_speech_file.route('/files', methods=['DELETE'])
@exception_handle
def delete_files():
    path = request.args.get('path', "", type=str)
    S3Resource.delete_file(S3Resource(), path)
    return jsonify(code=0, message='ok', data=None)


@api_speech_file.route('/files/upload', methods=['POST'])
@exception_handle
@provide_session
@provide_user
def upload_files(oa_user_name, session: Session = None):
    path = request.form.get('path', "", type=str)
    size = request.form.get('size', type=int)
    file = request.files.get('file')
    project_id = path.split('/')[0]
    project = Project.get_project(project_id, session)
    if project is None:
        return jsonify(code=500, message='project is not exist', data=None)
    if not project_id.isdigit():
        return jsonify(code=500, message='The path should start with the project id', data=None)
    projects = Project.get_projects_by_oa_user_name(oa_user_name)
    map_projects = map(Project.to_json, projects)
    permission = False
    if int(project_id) in [p["id"] for p in list(map_projects)]:
        permission = True
    if not permission:
        return jsonify(code=403, message='user is not Permissions', data=None)
    S3Resource.upload_file(S3Resource(), path, file, size)
    return jsonify(code=200, message='ok', data=None)

@api_speech_file.route('/files/git/upload', methods=['POST'])
@exception_handle
@provide_session
def upload_files_from_git(session: Session = None):
    # 路径
    project_name = request.form.get('j_project_name', "", type=str)
    git_project_name = request.form.get('git_project_name', "", type=str)
    git_branch_name = request.form.get('git_branch_name', "", type=str)
    git_user_name = request.form.get('git_user_name', "", type=str)
    # 权限
    j_user_name = request.form.get('j_user_name', "", type=str)
    # 文件
    size = request.form.get('size', type=int)
    file = request.files.get('file')

    if not project_name or project_name == '':
        return jsonify(code=500, message='project_name is must', data=None)
    if not git_project_name or git_project_name == '':
        return jsonify(code=500, message='git_project_name is must', data=None)
    project = Project.get_project_by_name(project_name, session)
    if project is None:
        return jsonify(code=500, message='project is not exist', data=None)
    project_id = project.id
    projects = Project.get_projects_by_oa_user_name(j_user_name)
    map_projects = map(Project.to_json, projects)
    permission = False
    if int(project_id) in [p["id"] for p in list(map_projects)]:
        permission = True
    if not permission:
        return jsonify(code=403, message='user is not Permissions', data=None)

    paths = []
    paths.append(str(project_id))
    paths.append("CICD")
    paths.append(git_project_name)
    if git_branch_name:
        paths.append(git_branch_name)
    if git_user_name:
        paths.append(git_user_name)
    path = os.path.join(*paths)
    path = path + "/"
    S3Resource.upload_file(S3Resource(), path, file, size)
    return jsonify(code=200, message='ok', data=None)


@api_speech_file.route('/files/download', methods=['GET'])
@exception_handle
def download_files():
    path = request.args.get('path', "", type=str)
    return S3Resource().download_file(path)


@api_speech_file.route('/files/read', methods=['GET'])
@exception_handle
def read_file():
    path = request.args.get('file_path', "", type=str)
    type = path.split(".")[-1]
    if type != "py" and type != "sh" and type != "conf" and type != "properties":
        return jsonify(code=400, message="Only support shell/python/conf/properties file", data=None)
    context = S3Resource().read_file(path)
    return jsonify(code=0, message='ok', data=context)


@api_speech_file.route('/files/rename', methods=['POST'])
@exception_handle
def rename_file():
    source_file = request.args.get('source_file', default=None, type=str)
    target_folder = request.args.get('target_folder', default=None, type=str)
    file_name = request.args.get('file_name', default=None, type=str)
    if source_file and target_folder and file_name:
        S3Resource().rename_file(source_file, target_folder, file_name)
        return jsonify(code=0, message='ok', data=None)
    else:
        return jsonify(code=400, message="source_file and target_file can not be none", data=None)